import { Component, OnInit, Output, EventEmitter, Input, forwardRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { RecipesManageService } from '../../../../shared/services/recipes.service';
import { ChannelManageService } from '../../../../shared/services/channel.service';
import { LabelManageService } from '../../../../shared/services/label.service';
import { MaterialManageService } from '../../../../shared/services/material.service';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { UtilsService } from '../../../../shared/services/utils.service';


import {environment} from '../../../../../environments/environment';

const uploadIndex = false;

@Component({
  selector: 'app-detail-article',
  templateUrl: './detail-article.component.html',
  styleUrls: ['./detail-article.component.scss']
})

export class DetailArticleComponent implements OnInit {

  validateForm: FormGroup;

  uploadFile: any;
  textChange: Boolean = false;

  editor: any;

  fileList = [];
  previewImage = '';
  previewVisible = false;

  _loading: any = 0;

  imgIndex: any = [];

  editorContent: any;
  defaultModules = {
    toolbar: [
      ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
      // ['blockquote', 'code-block'],

      // [{ 'header': 1 }, { 'header': 2 }],               // custom button values
      // [{ 'list': 'ordered'}, { 'list': 'bullet' }],
      // [{ 'script': 'sub'}, { 'script': 'super' }],      // superscript/subscript
      // [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
      // [{ 'direction': 'rtl' }],                         // text direction

      // [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
      [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

      [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
      [{ 'font': [] }],
      [{ 'align': [] }],

      // ['clean'],                                         // remove formatting button

      ['link', 'image', 'video']                         // link and image, video
    ]
  };

  modelType: any;
  activeType: any;
  articleParams: any;
  fileUrl: String;
  constructor(
    private route: ActivatedRoute,
    private router: Router,
    private utilsService: UtilsService,
    private _message: NzMessageService,
    private materialManageService: MaterialManageService,
    private labelManageService: LabelManageService,
    private channelManageService: ChannelManageService,
    private recipesManageService: RecipesManageService,
    private fb: FormBuilder
  ) {
    this.fileUrl = environment.apiBaseUrl + 'admin/file/upload';
    this.validateForm = this.fb.group({
      formLayout: [ 'horizontal' ],
      recipesName : [ null, [ Validators.required ] ],
    });
  }

  ngOnInit() {
    this.reset();

    // 解析获得参数导入
    this.route.queryParams
        .subscribe((pam: any) => {
          // console.log('article', pam);
          if (pam['type'] === 'see') {
            this.modelType = 'see';
          } else {
            this.modelType = 'edit';
          }
          this.activeType = pam['active'] === 'edit' ? 'edit' : 'see';
          if (pam) {
            this.recipesManageService.getRecipe(pam['id']).subscribe(res => {
              // console.log(res);
              if (res['code'] === '0') {
                this.articleParams.id = pam['id'];
                this.articleParams.description = res['data']['description'];
                this.articleParams.images = res['data']['images'];
                this.articleParams.details = res['data']['details'];
                // 回填照片数据
                let uid = 0;
                let imgList = [];
                this.articleParams.images.forEach(img => {
                  uid--;
                  const imgName = img['value'].substr(img['value'].lastIndexOf('/') + 1);
                  imgList.push({
                    uid: uid,
                    name: imgName,
                    status: 'done',
                    url: img['value'],
                    thumbUrl: img['value'],
                  });
                });
                this.fileList = imgList;
                // console.log(this.fileList);
                // console.log(this.articleParams);
                // console.log(this.previewImage);
              }
            });
          }
        });
  }

  reset() {
    this.articleParams = {
      id: '',
      description: '',
      images: [],
      details: '',
      oldDetails: '',
    };
  }

  handlePreview = (file) => {
    // console.log(file);
    this.previewImage = file.url || file.thumbUrl;
    this.previewVisible = true;
  }

  submitForm() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[ i ].markAsDirty();
    }
  }

  handleEditorCreated(editorInstance: any) {
    // console.log('handleEditorCreated', editorInstance);
    // console.log(editorInstance);
    this.editor = editorInstance;
    let toolbar = editorInstance.getModule('toolbar');
    toolbar.addHandler('image', this.showImageUI);
  }

  showImageUI() {
    return document.getElementById('articleFile').click();
  }

  // 上传图片
  articleFileChange(e) {
    // console.log(e.target.files);
    // e.target.files
    let ajaxIndex = 0;        // 当前图片提交的序号
    let paramsImgArr = [];    // 提交图片数据
    let callbackImgArr = [];  // 反馈的url图片
    // let timerBol = false;
    // 重新组装图片数组
    Object.values(e.target.files).forEach((imgItem, index) => {
      paramsImgArr.push({
        index: index,
        img: imgItem
      });
    });
    // 把获得的图片进行提交保存
    let setImg = (arr) => {
      const range = this.editor.getSelection();
      // console.log(arr);
      arr.forEach((item, index) => {
        let imgObj = arr.find(i => i['index'] === ((arr.length - 1) - index));
        if (imgObj) {
          this.editor.insertEmbed(range.index, 'image', imgObj.res.url, 'user');
        }
      });
    };
    // 对新数组进行图片提交
    paramsImgArr.forEach((item) => {
      const param = {
        fileType: 'image',
        file: item['img']
      };
      this.utilsService.postUploadFiles(param).subscribe(res => {
        ajaxIndex++;
        // console.log(res);
        if (res['state'] === 'SUCCESS') {
          // const img = `<img src="${res['url']}"/>`;
          // this.articleParams.details = img + this.articleParams.details;
          callbackImgArr.push({
            res: res,
            index: item.index
          });
        }
        if (!this.textChange) {
          this.textChange = true;
          this.loaddingGo();
        }
        // console.log(ajaxIndex)
        // console.log(paramsImgArr.length)
        if (ajaxIndex === paramsImgArr.length) {
          const timerd = setTimeout(() => {
            this._loading = 0;
            this.textChange = false;
            // this.articleParams.details += img;
            // console.log(callbackImgArr);
            setImg(callbackImgArr);
            clearInterval(timerd);
          }, 5000);
        }
      });
    });
  }

  loaddingGo() {
    const timer = setInterval(() => {
      if (this._loading < 100) {
        this._loading += 2;
      } else {
        clearInterval(timer);
      }
    }, 100);
  }

  handleSelection(e) {
    const that = this;
    // console.log('handleSelection', e);
    // this.textChange  = false;
    // setInterval(() => {
    //   that.textChange  = true;
    // }, 100);
  }

  handleChange(e) {
    const that = this;
    // console.log(this.fileList);
    // console.log('handleChange', e);
    // console.log('img list:', this.fileList);
    // let str = JSON.stringify(that.articleParams.details);
    // that.articleParams.details = JSON.parse(str);
    // that.articleParams.details += '<p></p>';
    // let str = JSON.parse(JSON.stringify(this.articleParams.details));
    // // 匹配所有的 img 补上 /
    // let img = str.replace(/<img src=\"([^\"]*?)\">/gi, (str) => {
    //   console.log(str);
    //   return str.replace(/\>$/g, (s) => '/> ');
    // });
    // console.log(img);
    // that.articleParams.details += img;
    // console.log(str);
    // 当前添加对象 e.delta.ops
    // e.delta.ops.forEach((s, i) => {
    //   if (s.insert) {
    //     if (s.insert.image) {
    //       console.log('要替换图片了', i);
    //       // this.articleParams.details.replace(/<img src=\"([^\"]*?)\">/gi, (str) => {
    //       //   console.log(str)
    //       // });
    //     }
    //   }
    // });
    // const imgSum = '<img src="data:image/jpeg;base64';
    // const sum = this.articleParams.details.match(/data:image\/(jpeg|png|gif);base64,/g);
    // console.log(sum);
  }

  upload(file): void {
    // console.log(file);
    const param = {
      fileType: 'image',
      file: file['originFileObj']
    };
    this.utilsService.postUploadFiles(param)
        .subscribe(res => {
          // console.log(res);
          if (res['state'] === 'SUCCESS') {
            this.articleParams.images.push(res['url']);
            if (this.imgIndex.length === this.fileList.length) {
              this.save();
            }
          }
        });
  }

  saveActive() {
    const that = this;
    // 判断需不需要去上传图片
    if (this.fileList.length > 0) {
      let bool = false; // size
      this.fileList.forEach(item => {
        if (item['size']) {
          bool = true;
        }
      });
      if (bool) {
        // 这边进行过滤，去掉没有的图片
        this.imgIndex = this.fileList;
        this.articleParams.images = [];
        this.fileList.forEach((files) => {
          if (!files['size']) {
            this.articleParams.images.push(files['url']);
          }
          ((file) => {
            that.upload(file);
          })(files);
        });
      } else {
        that.articleParams.images = [];
        that.fileList.forEach(item => {
          that.articleParams.images.push(item['url']);
        });
        that.save();
      }
    } else {
      this.articleParams.images = [];
      that.save();
    }
  }

  save() {
    // console.log('跑完图片了');
    // console.log(this.articleParams);
    if (!this.articleParams.description) {
      this.articleParams.description = '';
    }
    if (!this.articleParams.details) {
      this.articleParams.details = '';
    }

    // 后台返回两张图片，判断如果有旧图，就去取他的value值替换，上传
    this.articleParams.images.forEach((img, index) => {
      // console.log(img);
      if (img.value) {
        this.articleParams.images[index] = img['value'];
      }
    });

    this.recipesManageService.postUpdateRecipesInfo(this.articleParams).subscribe(res => {
      // console.log(res);
      if (res['code'] === '0') {
        this._message.success('修改图文信息成功！', {nzDuration: 2000});
        this.goback();
      } else {
        this._message.error('修改图文信息失败！错误：' + res['msg'], {nzDuration: 2000});
      }
    });
  }

  goback() {
    this.router.navigate(['../'], { relativeTo: this.route, queryParamsHandling: 'preserve' });
  }

  // 限制用户上传图片
  imgUpload = (file: File) => {
    const isJPG = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/jpg';
    if (!isJPG) {
      this._message.error('请上传jpg、png、jpeg格式的图片!');
    }
    const isLt1M = file.size / 1024 / 1024 < 1;
    if (!isLt1M) {
      this._message.error('图片过大，请重新上传！');
    }
    return isJPG && isLt1M;
  }

}
